import ini
import xlrd
import xlwt
import War3metadata
import sys
import re
import os
def ini2xl(ini_path,xl_path) -> None:
    consult = War3metadata.consult()
    new_book = xlwt.Workbook(encoding = 'ascii')
    _ini_data = ini.importIni(ini_path)
    _type = _ini_data['_type']
    ws = new_book.add_sheet(_type)
    attributes = ['_parent'] + list(consult[_type].keys())
    attributes.remove('w2lobject')
    if _type in ['ability','doodad','upgrade']:
        for _id in ['a','b','c','d','e','f','g','h','i']:
            attributes.append('data'+_id)
    for attribute in attributes:
        try:
            ws.write(1,attributes.index(attribute)+1,label = attribute)
            ws.write(0,attributes.index(attribute)+1,label = consult[_type][attribute]['displayname'])
        except KeyError:
            pass

    index = 2
    for obj in _ini_data['objs']:
        ws.write(index,0,label = obj['id'])
        for attribute in attributes:
            if attribute in obj:
                ws.write(index,attributes.index(attribute)+1,label = str(obj[attribute]))
        index += 1
    try:
        new_book.save(xl_path)
    except OSError:
        print('错误的输出地址或文件被占用')

def xl2ini(xl_path) -> None:
    _book = xlrd.open_workbook_xls(xl_path)
    _sheet_names = _book.sheet_names()
    consult = War3metadata.consult()
    for name in _sheet_names:
        _sheet = _book.sheet_by_name(name)
        if name in ['ability','buff','unit','item','upgrade','doodad','destructable']:
            _sheet_data = {'_type' : name,'obj' : []}
            attributes = ['_parent'] + list(consult[name].keys())
            if name in ['ability','doodad','upgrade']:
                for _id in ['a','b','c','d','e','f','g','h','i']:
                    attributes.append('data'+_id)
            for _id in _sheet.col_values(0):
                if len(_id) == 4:
                    _dict = {'id' : _id}
                    for col in range(1,_sheet.row_len(_sheet.col_values(0).index(_id))):
                        _attribute = _sheet.cell_value(1,col)
                        _value = _sheet.cell_value(_sheet.col_values(0).index(_id),col)
                        if len(_value) > 0 and _attribute in attributes:
                            if _attribute == '_parent' :
                                _dict[_attribute] = "\"%s\"" % _value
                            elif _attribute not in consult[name]:
                                exec("_dict[_attribute] = %s" % (_value))
                            elif 'repeat' in consult[name][_attribute]:
                                exec("_dict[_attribute] = %s" % (_value))
                            else :
                                data_type = consult[name][_attribute]['type']
                                if data_type == 1:
                                    _dict[_attribute] = int(_value)
                                elif data_type == 2:
                                    _dict[_attribute] = float(_value)
                                elif data_type == 3:
                                    _dict[_attribute] = "\"%s\"" % _value
                    _sheet_data['obj'].append(_dict)
            _str = ''
            for obj in _sheet_data['obj']:
                for parameter in obj:
                    if parameter == 'id':
                        _str += "[%s]\n" % (obj[parameter])
                    else:
                        _str += "%s = %s\n" % (parameter,str(obj[parameter]))
            with open(os.path.split(os.path.abspath(xl_path))[0] + "\\%s.ini" % (name),'w',encoding='utf-8') as fi:
                fi.write(_str)
if __name__ == "__main__":
    # ini_path = r'E:\Work_War3\War3MoeHero\MoeHero-master\MoeHero-master\logic_test\table\destructable.ini'
    # ini2xl(ini_path,"weng.xls")
    xl2ini("weng.xls")